<template>
  <div class="openlayers">
    <div id="map">
      <!--    地图弹窗B-->
      <!--  -->
      <div style="display: none">
        <div id="popup" class="ol-popup">
          <div class="closer" id="popup-closer" @click.stop="closer">
            <i style="color: #fff; font-size: 0.24rem" class="el-icon-close"></i>
          </div>

          <div class="pup_soc">
            <div class="binf-popup">
              <div><span>网格编号</span> </div>
              <div><span>{{ popObj.gridId }}</span></div>
            </div>
            <div class="binf-popup">
              <div><span>面积</span> </div>
              <div><span>{{ popObj.showArea }}亩</span></div>
            </div>
            <div class="binf-popup">
              <div><span>责任领导</span> </div>
              <div><span>{{ popObj.leader }}</span></div>
            </div>
            <div class="binf-popup">
              <div><span>网格负责人</span> </div>
              <div><span>{{ popObj.gridOwner }}</span></div>
            </div>
            <div class="binf-popup">
              <div><span>网格员</span> </div>
              <div><span>{{ popObj.gridStaff }}</span></div>
            </div>
            <div class="binf-popup">
              <div><span>管护员</span> </div>
              <div><span>{{ popObj.custodian }}</span></div>
            </div>
            <div class="binf-popup">
              <div><span>风险隐患</span> </div>
              <div><span>{{ popObj.riskSituation }}</span></div>
            </div>
          </div>


          <div style="height: 0.16rem; border-bottom: 1px solid rgba(46, 255, 242, 0.6);"></div>

          <div id="pie-popup"></div>

          <div style="height: 0.16rem;"></div>

          <div style="display: flex;justify-content: flex-end;">
            <el-button @click.stop="gopar()" size="small" type="primary"
              style="background-color:rgba(46, 255, 242, 0.40);">查看详情</el-button>
          </div>

        </div>
      </div>
      <!--    地图弹窗E-->
    </div>

  </div>
</template>
 
<script>
import * as echarts from "echarts";
import olMap from "ol/Map";
import View from "ol/View";
import * as olProj from "ol/proj";
import { Vector as VectorSource, XYZ } from "ol/source";
import MousePosition from 'ol/control/MousePosition';
import { createStringXY } from 'ol/coordinate';
import { defaults as defaultControls, FullScreen } from 'ol/control';
import { Heatmap as HeatmapLayer, Image as ImageLayer, Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import ImageWMS from 'ol/source/ImageWMS';
import { Circle as CircleStyle, Fill, Stroke, Style, Text, Icon } from 'ol/style';
import GeoJSON from "ol/format/GeoJSON";
import Overlay from "ol/Overlay";
import "ol/ol.css";
// 
import http from '../utils/http'
import api from '../utils/api'
export default {
  name: "openlayers",
  data() {
    return {
      areaId: "",
      Map: null,
      totalMap: {},
      puplay: null,
      popObj: {},
      dataList: []
    }
  },
  created() {
    this.areaId = window.sessionStorage.getItem('areaId');
  },
  mounted() {
    this.init();
  },
  methods: {
    async getbadalingGrid() {
      let res = await http.get(api.badalingGrid + this.areaId)
      if (res.data.code == '200') {
        let data = res.data.data;
        this.drawWMS(data.id, data.layerUrl, data.layerName, data.styleId, data.cql)
      }
    },
    init() {
      http.get(api.area + this.areaId).then(res => {
        let mapConfig = res.data.mapConfig;
        let center = [115.9871, 40.3230];
        // let maxExtent = boundingExtent([[115.3701, 37.4570], [115.8590, 37.7686]]);
        let container = document.getElementById('popup');
        this.puplay = new Overlay({
          element: container,
          autoPan: true,
          offset: [0, -10],
          autoPanAnimation: {
            duration: 250
          }
        });
        this.Map = new olMap({
          target: 'map',
          layers: [],
          overlays: [this.puplay],
          controls: defaultControls({
            attribution: false,
            zoom: false,
            rotate: false
          }).extend([]),
          view: new View({
            //设置中心点
            center: olProj.fromLonLat(center),
            zoom: mapConfig.level,
            maxZoom: 17
            // extent: olProj.transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857')
          })
        });
        //添加底图
        this.totalMap["bsaeMap"] = new TileLayer({
          source: new XYZ({
            url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=f24cec70606332017dcd39a4fb60dd11'
          })
        })
        this.Map.addLayer(this.totalMap["bsaeMap"]);
        //移入鼠标显示经纬度
        var mousePositionControl = new MousePosition({
          coordinateFormat: createStringXY(4),
          projection: 'EPSG:4326',
          className: 'custom-mouse-position',
          target: document.getElementById('mouse-position'),
          undefinedHTML: '&nbsp;'
        });
        this.Map.addControl(mousePositionControl);
        this.getbadalingGrid();
        // 创建点击事件
        var _self = this;
        this.Map.on('singleclick', function (event) {
          let lat = olProj.transform(event.coordinate, 'EPSG:3857', 'EPSG:4326');
          let coordinate = event.coordinate;
          http.get(api.gridInfo, {
            areaId: _self.areaId,
            lon: lat[0],
            lat: lat[1],
            startTime: "",
            endTime: ""
          }).then(res => {
            if (res.data.code = '200' && res.data.message == "查询成功!") {
              _self.popObj = res.data.data.gridInfo;
              _self.dataList = res.data.data.dataList;
              _self.puplay.setPosition(coordinate);
              _self.puplay.setPositioning("bottom-center");
              let ob = res.data.data.countInfo;
              let aob = [];
              for (let k in ob) {
                let z = {
                  value: ob[k], name: k
                }
                aob.push(z)
              }
              _self.drawpie('pie-popup', aob)
            }
          })
        });
      })
    },
    //绘制wms类型
    drawWMS(item, url, name, styleId, cql) {
      if (typeof (this.totalMap[item]) != "undefined") {
        this.Map.removeLayer(this.totalMap[item]);
        delete this.totalMap[item];
      }
      let params = {
        'LAYERS': name,
        'STYLES': styleId,
        'CQL_FILTER': "[" + cql + "]"
      };

      this.totalMap[item] = new ImageLayer({
        source: new ImageWMS({
          url: url,
          params: params,
          serverType: 'geoserver'
        })
      })
      this.Map.addLayer(this.totalMap[item]);
      if (item == 'twocwms') {
        this.totalMap[item].setZIndex(8);
      }

    },
    //绘制geojson类型
    previewshape(data, id) {
      var vm = this;
      //判断是否已经存在相同id的图层 如果有删掉，再重新绘制
      if (typeof (this.totalMap[id]) != "undefined") {
        this.Map.removeLayer(this.totalMap[id]);
        delete this.totalMap[id];
      }
      let styleFunction = function () {
        return function (feature, resolution) {
          //点
          if (feature.getGeometry().getType() == 'Point') {
            if (feature.get('fillColor').indexOf('#') != -1) {
              var point = new Style({
                image: new CircleStyle({
                  radius: feature.get("radius"),
                  fill: new Fill({
                    color: feature.get("fillColor")
                  }),
                  stroke: new Stroke({
                    color: feature.get("borderColor"),
                    width: feature.get("size")
                  })
                }),
                text: new Text({
                  font: '12px Calibri,sans-serif',
                  text: feature.get('text'),
                  fill: new Fill({
                    color: feature.get('fillColor')
                  }),
                  offsetY: 15,
                  stroke: new Stroke({
                    color: 'white',
                    width: 1
                  }),
                })
              })
            } else {
              var point = new Style({
                image: vm.addImage(feature, resolution),
                text: new Text({
                  font: '12px Calibri,sans-serif',
                  text: feature.get('text'),
                  fill: new Fill({
                    color: feature.get('fillColor')
                  }),
                  offsetY: 15,
                  stroke: new Stroke({
                    color: 'white',
                    width: 1
                  }),
                })
              })
            }
            return [point]
          }
          if (feature.getGeometry().getType() == 'MultiPoint') {
            var MultiPoint = new Style({
              image: new CircleStyle({
                radius: 5,
                fill: new Fill({
                  color: feature.get("fillColor")
                }),
                stroke: new Stroke({
                  color: feature.get("borderColor"),
                  width: feature.get("size")
                })
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: feature.get('fillColor')
                }),
                offsetY: 15,
                stroke: new Stroke({
                  color: 'white',
                  width: 1
                }),
              })
            })
            return [MultiPoint]
          }
          //面
          if (feature.getGeometry().getType() == 'MultiPolygon') {
            var MultiPolygon = new Style({
              stroke: new Stroke({
                color: feature.get('borderColor'),
                width: 3
              }),
              fill: new Fill({
                color: feature.get("fillColor")
              }),
              text: new Text({
                font: '16px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: feature.get('textColor')
                }),
                stroke: new Stroke({
                  color: feature.get('textColor'),
                  width: 1
                })
              })
            })
            return [MultiPolygon]
          }
          if (feature.getGeometry().getType() == 'Polygon') {
            var Polygon = new Style({
              stroke: new Stroke({
                color: feature.get('borderColor'),
                width: 3
              }),
              fill: new Fill({
                color: feature.get("fillColor")
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: feature.get('borderColor')
                }),
                stroke: new Stroke({
                  color: 'white',
                  width: 3
                }),
              })
            })
            return [Polygon]
          }
          //线
          if (feature.getGeometry().getType() == 'LineString') {
            var LineString = new Style({
              stroke: new Stroke({
                color: feature.get('borderColor'),
                width: feature.get("size") + 3
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: 'white'
                }),
                stroke: new Stroke({
                  color: 'block',
                  width: 2
                }),
              })
            })
            return [LineString]
          }
          //多线
          if (feature.getGeometry().getType() == 'MultiLineString') {
            var MultiLineString = new Style({
              stroke: new Stroke({
                color: feature.get('borderColor'),
                width: feature.get("size") + 3
              }),
              text: new Text({
                font: '12px Calibri,sans-serif',
                text: feature.get('text'),
                fill: new Fill({
                  color: 'white'
                }),
                stroke: new Stroke({
                  color: 'block',
                  width: 2
                }),
              })
            })
            return [MultiLineString]
          }
        }
      };
      let geojsonObject = {
        'type': 'FeatureCollection',
        'crs': {
          'type': 'name',
          'properties': {
            'name': 'EPSG:4326'
          }
        },
        'features': []
      };
      this.vectorSource = new VectorSource({
        features: (new GeoJSON(
          {
            defaultDataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:3857'
          }
        )).readFeatures(geojsonObject)
      });
      this.totalMap[id] = new VectorLayer({
        source: this.vectorSource,
        style: styleFunction()
      });
      let sources = this.totalMap[id].getSource();
      data.forEach((e => {
        sources.addFeatures(
          (new GeoJSON({
            defaultDataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:3857'
          })).readFeatures({
            "id": e.id,
            "properties": {
              "borderColor": e.borderColor,
              "fillColor": e.fillColor,
              "iconSrc": e.iconSrc,
              "data": e.data
            },
            'type': 'Feature',
            'geometry': e.geojson
          }))
      }));
      this.totalMap[id].set("altitudeMode", "clampToGround");
      this.Map.addLayer(this.totalMap[id]);

      //绘制点线的时候  给  图层id 加上 @Point||@LineString  然后给点线的层级设高 高于面的
      // 避免显示地图弹窗的时候 面遮住点线 点击不到 点线的feature
      var drawType = id.split("_");
      if (drawType[drawType.length - 1] == 'Point') {
        this.totalMap[id].setZIndex(9);
      }
      if (drawType[drawType.length - 1] == 'LineString') {
        this.totalMap[id].setZIndex(9);
      }

    },
    //点类型绘制图标 需要定位图标位置
    //地图图标位置处理函数
    addImage(feature, resolution) {
      let src = feature.get('iconSrc');
      let anchor = [0, 1];
      //根据图标文件名 设置定位点  地图上放置的图标更改文件名即可保持一致
      if (src != '') {
        if (src.indexOf('anchor_bottom_center') != -1) {
          anchor = [0.5, 1];
        } else if (src.indexOf('anchor_bottom_left') != -1) {
          anchor = [0, 1];
        } else if (src.indexOf('anchor_bottom_right') != -1) {
          anchor = [1, 1];
        } else if (src.indexOf('anchor_center_center') != -1) {
          anchor = [0.5, 0.5];
        } else if (src.indexOf('anchor_top_center') != -1) {
          anchor = [0.5, 0];
        } else if (src.indexOf('anchor_top_left') != -1) {
          anchor = [0, 0];
        } else if (src.indexOf('anchor_top_right') != -1) {
          anchor = [1, 0];
        }
        return new Icon({
          src: feature.get('iconSrc'),
          scale: 0.8,
          anchor: anchor,
        });
      }
    },
    //关闭弹窗
    closer() {
      var closer = document.getElementById('popup-closer');
      this.puplay.setPosition(undefined);
      closer.blur();
      if (typeof (this.totalMap.grids) != "undefined") {
        this.Map.removeLayer(this.totalMap.grids);
        delete this.totalMap.grids;
      }
      return false
    },
    flyPoint(data) {
      this.Map.getView().setCenter(olProj.fromLonLat(data));
      this.Map.getView().setZoom(14);
    },
    delPoint(id) {
      if (typeof (this.totalMap[id]) != "undefined") {
        this.Map.removeLayer(this.totalMap[id]);
        delete this.totalMap[id];
      }
    },
    drawpie(demo, data) {
      let myChart = echarts.getInstanceByDom(document.getElementById(demo));
      if (myChart == null) {
        myChart = echarts.init(document.getElementById(demo));
      }

      let option = {
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['30%', '50%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              fontSize: 14,
              color: '#fff',
              formatter(param) {
                return param.name + '(' + param.value + ')';
              }
            },
            data: data
          }
        ]
      };
      myChart.setOption(option);
      setTimeout(function () {
        myChart.resize();
      }, 100);
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    },
    // 查看点位
    gopar() {
      this.$parent.opensjo(this.dataList);
    }
  }
}
</script>
 
<style scoped>
.openlayers {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
}

#map {
  width: 100%;
  height: 100%;
}

.track {
  width: calc(100% - 0.32rem);
  height: 0.46rem;
  padding: 0 0.16rem;
  display: flex;
  align-items: center;
  position: absolute;
  left: 0.16rem;
  bottom: 0.16rem;
  z-index: 3;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0px 0px 16px rgba(0, 58, 123, 0.2);
  border-radius: 8px;
  overflow: hidden;
  box-sizing: border-box;
}

#popup {
  width: 4rem;
  padding: 0.16rem;
  border-radius: 8px;
  background: rgba(0, 77, 72, 0.90);
}

#popup::before {
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translate(-50%);
  content: "";
  border-top: 10px solid rgba(0, 77, 72, 0.90);
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  z-index: 2;
}

.closer {
  font-weight: 700;
  position: absolute;
  top: 4px;
  right: 4px;
  z-index: 3;
  cursor: pointer;
}

.masking {
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(255, 255, 255, 0.1);
  overflow: hidden;
}

.pup_soc {
  width: 100%;
  height: 2rem;
  margin-top: 0.16rem;
  overflow-y: auto;
  overflow-x: hidden;
}


.pup_soc::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 4px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}

.pup_soc::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 2px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(46, 255, 242, 0.6);
}
</style>

<style>
.custom-mouse-position {
  font-size: 16px;
  font-weight: 700;
  color: #fff;
  position: absolute;
  bottom: 5px;
  right: 16px;
}

.binf-popup {
  font-size: 0.16rem;
  line-height: 0.35rem;
  color: #fff;
  display: flex;
  /* align-items: center; */
  /* justify-content: space-between; */
  flex-shrink: 0;
  overflow: hidden;
}

.binf-popup>div:nth-child(1) {
  width: 1rem;
  font-weight: 700;
}

.binf-popup>div:nth-child(2) {
  width: calc(100% - 1rem);
}

#pie-popup {
  width: 100%;
  height: 150px;
}
</style>